import axios from 'axios';
import { Notify } from 'vant';
import qs from 'qs';
import store from '@/store';

let baseURL='http://localhost:8081/api';

const service = axios.create({
  baseURL,
  timeout: 5000 // 请求超时时间
});

//请求
service.interceptors.request.use(config => {
  if (store.state.token) {
    config.headers['authorization'] = store.state.token;
  }
  return config;
});

//响应
// service.interceptors.response.use(response => {
//   const data = response.data;
//   if (data.code === 200) {
//     return Promise.resolve(response);
//   } else {
//     Notify({ type: 'danger', message: response.data.message || '' });
//     return Promise.reject(response);
//   }
// });
//响应
service.interceptors.response.use(
  response => {
    const res = response.data
    return response
  },
  async error => {
    Notify({ type: 'danger', message: response.data.message || '网络出现错误' });
    return Promise.reject(error)
  })

let http = {};

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.get = function(url, params = null) {
  return new Promise((resolve, reject) => {
    service
      .get(url, { params })
      .then(res => {
        resolve(res);
      })
      .catch(e => {
        reject(e);
      });
  });
};

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

http.post = function(url, params) {
  return new Promise((resolve, reject) => {
    service
      .post(url,params)
      .then(res => {
        resolve(res);
      })
      .catch(e => {
        reject(e);
      });
  });
};

export default http;

